package com.yootk.config;

import com.yootk.webflux.websocket.EchoHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket配置类
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public HandlerMapping websocketMapping(@Autowired EchoHandler echoHandler) {
        Map<String, WebSocketHandler> map = new HashMap<>();                // 配置映射集合
        map.put("/websocket/{token}", echoHandler);                         // 配置映射路径
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();    // 映射处理
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);                       // 配置映射级别
        mapping.setUrlMap(map);     // 设置映射路径
        return mapping;             // 返回映射配置
    }

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();   // WebSocket适配器
    }
}
